package com.gking.processHarvest.service.ChatHistory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.processHarvest.common.BaseContext;
import com.gking.processHarvest.common.CustomException;
import com.gking.processHarvest.common.Res;
import com.gking.processHarvest.entity.ChatHistory;
import com.gking.processHarvest.mapper.ChatHistoryMapper;
import com.gking.processHarvest.utils.SseServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements ChatHistoryService {


    /**
     * 更新接收用户未读消息数量
     *
     * @param userId 用户id
     * @return s
     */
    public boolean refreshNotReadCount(String userId) {
        LambdaQueryWrapper<ChatHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatHistory::getReceiverId, userId);
        wrapper.eq(ChatHistory::getIsRead, 1);
        wrapper.eq(ChatHistory::getIsDelete, 0);

        return SseServer.notReadCountEvent(userId, this.count(wrapper));
    }


    /**
     * 发送消息
     *
     * @param receiverId 接收者id
     * @param message    消息详情
     * @return s
     */
    @Override
    public Res<String> sendChattingMessage(String receiverId, String message) {
        //设置聊天记录
        ChatHistory chatHistory = new ChatHistory();
        chatHistory.setMessage(message);
        chatHistory.setReceiverId(receiverId);
        chatHistory.setMasterId(BaseContext.getCurrentId());
        chatHistory.setCreateTime(LocalDateTime.now());
        chatHistory.setType("text");

        //聊天时，给自己和接收信息者各发一条消息
        boolean b = SseServer.chattingSendMessage(BaseContext.getCurrentId(), chatHistory);
        boolean status = SseServer.chattingSendMessage(receiverId, chatHistory);
        log.error("发送消息给自己的情况 ： {}", b);
        log.error("发送消息给接收者的情况 ： {}", status);

        //接收者暂不在线，则将消息设为未读保存至数据库
        if (!status) chatHistory.setIsRead(1);
        this.save(chatHistory);

        //更新接收用户未读消息数量
        refreshNotReadCount(receiverId);

        return Res.success("发送消息成功！");
    }


    /**
     * 检查 未读消息
     *
     * @return s
     */
    @Override
    public Res<String> checkChattingNotReceiveMessage() {
        //检查发给自己的消息是否有未读的
        LambdaQueryWrapper<ChatHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatHistory::getReceiverId, BaseContext.getCurrentId());
        queryWrapper.eq(ChatHistory::getIsRead, 1);
        queryWrapper.eq(ChatHistory::getIsDelete, 0);
        queryWrapper.orderByAsc(ChatHistory::getCreateTime);

        List<ChatHistory> list = this.list(queryWrapper);

        boolean sent = SseServer.sendNotReadRecordList(BaseContext.getCurrentId(), list);
        if (!sent) return Res.error("发送未读消息错误");

        if (!list.isEmpty()) {
            list.forEach(item -> item.setIsRead(0));
            this.updateBatchById(list);
        }

        //更新接收用户未读消息数量
        refreshNotReadCount(BaseContext.getCurrentId());

        return Res.success("获取未读消息成功！");
    }
}
